<template>
	<view>
		<view class="uni-form-item uni-column">
			<view class="title">老人姓名:</view>
			<view class="uni-input-wrapper">
				<input class="uni-input" type="text" placeholder="请输入老人姓名" v-model="elderName" />
			</view>
		</view>
		<view class="uni-form-item uni-column">
			<view class="title">老人身份证号:</view>
			<view class="uni-input-wrapper">
				<input class="uni-input" type="idcard" placeholder="请输入老人身份证号码" v-model="elderID" />
			</view>
		</view>
		<view class="uni-form-item uni-column">
			<view class="title">设备名称:</view>
			<view class="uni-input-wrapper">
				<input class="uni-input" type="text" placeholder="请输入设备名称" v-model="deviceName" />
			</view>
		</view>
		<!-- 		<view class="uni-form-item uni-column">
			<view class="title">设备主题:</view>
			<view class="uni-input-wrapper">
				<input class="uni-input" type="text" placeholder="请输入设备类型(例如:P38:1314343)"
					v-model="deviceTopic" />
			</view>
		</view> -->

		<view class="uni-form-item uni-column">
			<view class="title">设备型号:</view>
			<view class="uni-input-wrapper">
				<!-- <view class="uni-list-cell-db"> -->
				<picker class="uni-list-cell-db" @change="bindPickerChange" :value="modelIndex" :range="deviceModelArr">
					<view class="uni-input">{{deviceModelArr[modelIndex]}}</view>
				</picker>
				<!-- </view> -->
			</view>
		</view>
		<view class="uni-form-item uni-column">
			<view class="title">设备标识码（imei）:</view>
			<view class="uni-input-wrapper">
				<input class="uni-input" type="text" placeholder="请输入设备标识码" v-model="deviceImei" />
				<uni-icons class="scan-imei camera" size="25" color="#007aff" type="scan" @click="scanImei"></uni-icons>
			</view>

		</view>
		<view class="uni-form-item uni-column">
			<view class="title">设备厂商:</view>
			<view class="uni-input-wrapper">
				<input class="uni-input" type="text" placeholder="请输入设备厂商" v-model="manufacturer" />
			</view>
		</view>
		<view class="buttons">
			<button class="mini-btn" type="default" @click="testConnection()"
				:style="{width:countdownText? '150px' : '120px'}">测试信号{{countdownText}}</button>
			<button class="mini-btn" type="primary" @click="bindDevice()">绑定</button>
			<!-- 			<u-button class="mini-btn" type="info" @click="testConnection()">测试信号</u-button>
			<u-button class="mini-btn" type="primary" @click="bindDevice()">绑定</u-button> -->

		</view>
		<!-- 测试信号 弹出框 -->
		<uni-popup ref="popup" type="center" :animation="true">
			<view class="popup-content">
				<view>测试信号中，请确保设备已处于开机状态。</view>
				<view>预计还需{{countdownSec}}秒...</view>
				<button class="close-popup" @click="closePopup">隐藏窗口</button>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	import {
		bindPillBox,
		testPillboxSignal
	} from "../api/pillbox.js";
	export default {
		data() {
			return {
				elderName: "",
				elderID: "",
				deviceName: "智能药盒",
				// deviceTopic: "",
				deviceImei: "",
				manufacturer: "",
				deviceModelArr: ['请选择设备型号', 'P38', 'P39', 'P40'],
				modelIndex: 0,
				countdownSec: 0,
			}
		},
		computed: {
			// 设备主题 使用设备型号+设备imei拼接
			deviceTopic() {
				return this.deviceModelArr[this.modelIndex] + ":" + this.deviceImei;
			},
			// 倒数 文字提示
			countdownText() {
				return this.countdownSec == 0 ? '' : `(${this.countdownSec}秒)`
			}
		},
		methods: {
			scanImei() {
				console.log("点击了 扫码获取imei");
				uni.scanCode({
					success: (res) => {
						console.log("扫码成功")
						console.log(res.result)
						this.deviceImei = res.result;
					},
					fail: () => {
						console.log("扫码失败")
					}
				})
			},
			bindPickerChange(e) {
				this.modelIndex = e.detail.value;
			},
			// 测试信号
			async testConnection() {
				console.log("点了测试信号");
				// 检查设备信息填写情况
				if (this.deviceImei == '') {
					uni.showToast({
						title: '错误:未输入设备标识码',
						icon: 'none',
						duration: 2000
					})
					return
				}
				// 去除定时器，使用异步
				uni.showLoading({
					title:'正在搜索信号...'
				});
				const res = await testPillboxSignal(this.deviceImei);
				uni.hideLoading();
				if (res.code == 200) {
					uni.showToast({
						title: res.msg,
						icon: 'none',
						duration: 2000,
					})
				} else {
					uni.showToast({
						title: '测试信号失败',
						icon: 'none',
						duration: 3000,
					})
				}
				// 开始测试信号，倒数180秒
				// this.countdownSec = 8;
				// this.$refs.popup.open('center')
				// let that = this;
				// var countdownTimer = setInterval(async function() {
				// 	that.countdownSec -= 1;
				// 	console.log("setInterval还剩", that.countdownSec)
				// 	// 每隔五秒请求一次后端
				// 	if (that.countdownSec % 5 == 0) {
				// 		console.log("隔5秒查询一次");
				// 		const res = await testPillboxSignal(that.deviceImei);
				// 		// 找到信号 提前结束倒计时
				// 		// if (true) {
				// 		if (res.code == "200" || res.code == 200) {
				// 			console.log("清除定时器，关闭弹窗");
				// 			clearInterval(countdownTimer);
				// 			that.countdownSec = 0;
				// 			that.$refs.popup.close();
				// 			uni.showToast({
				// 				title: '信号连接正常',
				// 				icon: 'success',
				// 				duration: 2000,
				// 			})
				// 			return
				// 		}
				// 	};
				// 	// 没有找到信号 倒计时结束 清除定时器 报错
				// 	if (that.countdownSec == 0) {
				// 		console.log("清除定时器，关闭弹窗");
				// 		clearInterval(countdownTimer);
				// 		that.$refs.popup.close();
				// 		uni.showToast({
				// 			title: '未找到信号，请确认设备已开机',
				// 			icon: 'none',
				// 			duration: 3000,
				// 		})
				// 	}
				// }, 1000)
			},
			// 关闭倒计时弹窗
			closePopup() {
				this.$refs.popup.close();
			},
			// 绑定设备
			async bindDevice() {
				const bindingData = {
					idNumber: this.elderID,
					manufacturer: this.manufacturer,
					deviceName: this.deviceName,
					oldManName: this.elderName,
					imei: this.deviceImei,
					topic: this.deviceTopic
				}
				// 测试数据
				// const bindingData = {
				// 	idNumber: "130926194003082428",
				// 	manufacturer: "药盒厂商",
				// 	deviceName: "智能药盒",
				// 	oldManName: "杨运英",
				// 	imei: "862170067052843",
				// 	topic: "P38:862170067052843"
				// }
				console.log("发送给后台的数据:", bindingData);
				const res = await bindPillBox(bindingData);
				if (res.code == "200") {
					await uni.showToast({
						title: '绑定成功',
						icon: '',
						duration: 2000,
						mask: true
					});
					let timer = setTimeout(() => {
						clearTimeout(timer)
						uni.navigateTo({
							url: "/pages/homepage/ElderDeviceList/ElderList/index"
						})
					}, 2000)
				} else {
					uni.showModal({
						title:res.msg,
						confirmText:'关闭',
						showCancel:false,
					})
				}
				console.log("绑定res",res);
				// try {
				// 	const res = await bindPillBox(bindingData);
				// 	if (res.code == "200") {
				// 		await uni.showToast({
				// 			title: '绑定成功',
				// 			icon: '',
				// 			duration: 2000,
				// 			mask: true
				// 		});
				// 		let timer = setTimeout(() => {
				// 			clearTimeout(timer)
				// 			uni.navigateTo({
				// 				url: "/pages/work/olds/index"
				// 			})
				// 		}, 2000)
				// 	}
				// } catch (e) {
				// 	console.log("绑定失败,错误:");
				// 	console.log(e)
				// 	uni.showToast({
				// 		title: '绑定失败',
				// 		icon: 'error',
				// 		duration: 1500,
				// 		mask: true
				// 	})
				// }

			}
		},
		onLoad() {
			// 老人姓名 老人id 
			// 需要通过路由或者vuex获取，这里写死测试用
			// this.elderName = this.$mp.query.elderName;
			// this.elderID = this.$mp.query.elderId;
			this.elderName = "李四"
			this.elderID = "123456789123456789"
			this.deviceImei = "862170067052843"
		},
	}
</script>

<style>
	@import url(@/common/uni.css);

	view {
		font-size: 16px;
	}

	.mini-btn {
		/* width: 280rpx; */
		width: 120px;
		font-size: 16px;
	}

	.buttons {
		display: flex;
		/* 		flex-direction: row;
		align-content: space-between; */
		margin-top: 40rpx;

	}

	.scan-imei {
		margin-left: 20px;
	}

	.uni-input-wrapper {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		padding: 8px 13px;
		flex-direction: row;
		flex-wrap: nowrap;
		background-color: #FFFFFF;
		/* added */
		width: auto;
		margin: 0 20rpx;
		border-radius: 5px;
	}

	.uni-input {
		height: 28px;
		line-height: 28px;
		font-size: 15px;
		padding: 0px;
		flex: 1;
		background-color: #FFFFFF;
	}

	.countdown-message {
		width: 240px;
		height: 240px;
		border-radius: 5px;
	}

	.popup-content {
		position: relative;
		background-color: white;
		width: 200px;
		height: 200px;
		border-radius: 5px;
		padding: 10px 20px;
		color: #333;
	}

	.close-popup {
		position: absolute;
		width: 100px;
		bottom: 10px;
		left: 50px;
		font-size: 16px;
	}
</style>